//
//  UITextView-Extension.swift
//  Status
//
//  Created by Kylin on 16/3/28.
//  Copyright © 2016年 Kylin. All rights reserved.
//

import UIKit

extension UITextView {

    func getEmoticonString () -> String {
        // 1.根据customTextView中的属性字符串创建一个可变的属性字符串
        let attrMStr = NSMutableAttributedString(attributedString: attributedText)
        // 2.遍历可变属性字符串
        let range = NSRange(location: 0, length: attrMStr.length)
        
        attrMStr.enumerateAttributesInRange(range, options: []) { (dict , range, _) -> Void in
            
            // 因为表情文字属性为NSAttachment 所以可以截取出来
            if let attachment = dict["NSAttachment"] as? EmoticonAttachment where (attachment.chs != nil){
                // 将截取出来的范围替换成对应的字符串
                attrMStr.replaceCharactersInRange(range, withString: attachment.chs!)
            }
        }
        
        return attrMStr.string
    }
    
    func insertEmoticon(emoticon : Emoticon) {
        // 1.判断是否空白表情

        if emoticon.isEmpty {
            return
        }
        
        // 2.判断是否删除按钮
        if emoticon.isRemove {
            deleteBackward()
            return
        }
        
        // 3.emoji表情
        if emoticon.emojiCode != nil{
            // 3.1.获取光标所在的位置
            let range = selectedTextRange!
            
            // 3.2.将光标选中的位置替换成emojiCode
            replaceRange(range, withText: emoticon.emojiCode!)
            return
        }
        // 4.普通表情
        // 4.0.取出font
        let tempFont = font!
        
        // 4.1.获取光标所在的位置
        let range = selectedRange
        // 4.2.根据原有的文字,创建可变的属性字符串
        let attrMStr = NSMutableAttributedString(attributedString: attributedText)
        // 4.3.将图片转成属性字符串
        let attachment = EmoticonAttachment ()
        attachment.chs = emoticon.chs
        attachment.bounds = CGRect(x: 0, y: -3, width: tempFont.lineHeight, height: tempFont.lineHeight)
        attachment.image = UIImage(contentsOfFile: emoticon.pngPath!)
        let imageAttStr = NSAttributedString(attachment: attachment)
        // 4.4.将图片属性字符串替换到可变属性字符串中
        attrMStr.replaceCharactersInRange(range, withAttributedString: imageAttStr)
        // 4.5.显示属性字符串
        attributedText = attrMStr
        // 4.6.重置光标的位置
        selectedRange = NSRange(location: range.location + 1, length: 0)
        // 4.7.将字体的大小重置
        font = tempFont
    }
}
